package config

import (
	"log"
	"time"

	"github.com/spf13/viper"
)

// GlobalConfig 全局配置变量，用于在应用中访问配置
var GlobalConfig *Config

type Config struct {
	Server   ServerConfig   `mapstructure:"server"`
	Database DatabaseConfig `mapstructure:"database"`
	Redis    RedisConfig    `mapstructure:"redis"`
	JWT      JWTConfig      `mapstructure:"jwt"`
	CORS     CORSConfig     `mapstructure:"cors"`
	Log      LogConfig      `mapstructure:"log"`
	Security SecurityConfig `mapstructure:"security"`
}

type SecurityConfig struct {
	Password PasswordConfig `mapstructure:"password"`
	Login    LoginConfig    `mapstructure:"login"`
}

type PasswordConfig struct {
	MinLength      int  `mapstructure:"minLength"`
	MaxLength      int  `mapstructure:"maxLength"`
	RequireUpper   bool `mapstructure:"requireUpper"`
	RequireLower   bool `mapstructure:"requireLower"`
	RequireNumber  bool `mapstructure:"requireNumber"`
	RequireSpecial bool `mapstructure:"requireSpecial"`
}

type LoginConfig struct {
	MaxFailedAttempts int           `mapstructure:"maxFailedAttempts"`
	LockoutDuration   time.Duration `mapstructure:"lockoutDuration"` // 分钟
}

type ServerConfig struct {
	Port int    `mapstructure:"port"`
	Mode string `mapstructure:"mode"`
}

type DatabaseConfig struct {
	Host            string `mapstructure:"host"`
	Port            int    `mapstructure:"port"`
	Username        string `mapstructure:"username"`
	Password        string `mapstructure:"password"`
	DBName          string `mapstructure:"dbname"`
	Charset         string `mapstructure:"charset"`
	MaxIdleConns    int    `mapstructure:"maxIdleConns"`
	MaxOpenConns    int    `mapstructure:"maxOpenConns"`
	ConnMaxLifetime int    `mapstructure:"connMaxLifetime"` // 连接最大生命周期（秒）
	ConnMaxIdleTime int    `mapstructure:"connMaxIdleTime"` // 空闲连接最大生命周期（秒）
}

type RedisConfig struct {
	Host     string `mapstructure:"host"`
	Port     int    `mapstructure:"port"`
	Password string `mapstructure:"password"`
	DB       int    `mapstructure:"db"`
}

type JWTConfig struct {
	AccessSecret  string `mapstructure:"accessSecret"`
	RefreshSecret string `mapstructure:"refreshSecret"`
	AccessExpire  int    `mapstructure:"accessExpire"`
	RefreshExpire int    `mapstructure:"refreshExpire"`
}

type CORSConfig struct {
	AllowOrigins []string `mapstructure:"allowOrigins"`
	AllowMethods []string `mapstructure:"allowMethods"`
	AllowHeaders []string `mapstructure:"allowHeaders"`
}

type LogConfig struct {
	Path  string `mapstructure:"path"`
	Level string `mapstructure:"level"`
}

func Load() *Config {
	viper.SetConfigName("config")
	viper.SetConfigType("yaml")
	viper.AddConfigPath("./config")
	viper.AddConfigPath("../../config")

	if err := viper.ReadInConfig(); err != nil {
		log.Fatalf("读取配置文件失败: %v", err)
	}

	var cfg Config
	if err := viper.Unmarshal(&cfg); err != nil {
		log.Fatalf("解析配置文件失败: %v", err)
	}

	// 设置全局配置变量
	GlobalConfig = &cfg

	return &cfg
}
